package cn.hchaojie.camp.javafx.part2;

import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
 * 监听器模式：一方只要发送事件，事件如何处理，让另外一方负责
 * 
 * 好处，交互双方解耦，一方不需要知道另外一方的实现细节。
 * 
 * 如果事件处理改变时，只需要改变一方就可以
 * 
 * @author hchaojie
 *
 */
public class Interact2 extends Application {
	private List<ParentStageActionHandler> handlers = new ArrayList<>(); 
	
	private int id = 1;

	@Override
	public void start(Stage stage) throws Exception {
		Scene scene = new Scene(createContents());
		
		stage.setScene(scene);
		stage.show();
	}
	
	// 在这里创建页面布局
	private Parent createContents() {
		VBox box = new VBox(10);
		box.setAlignment(Pos.CENTER);
		
		Button btn = new Button("创建新窗口");
		btn.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				createStage(id++);
			}
		});
		
		Button color = new Button("设置颜色");
		color.setOnAction(e -> {
			for (ParentStageActionHandler handler: handlers) {
				handler.onSetColorClicked(Color.RED);
			}
		});
		
		Button close = new Button("关闭所有");
		close.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				for (ParentStageActionHandler handler: handlers) {
					handler.onCloseClicked();
				}
			}
		});
		
		box.getChildren().add(btn);
		box.getChildren().add(color);
		box.getChildren().add(close);

		return box;
	}

	private void createStage(int id) {
		ChildStage stage = new ChildStage(id);
		stage.show();
		handlers.add(stage);
	}

	public static void main(String[] args) {
		launch(args);
	}
	

	class ChildStage extends Stage implements ParentStageActionHandler {
		private VBox vbox;
		
		public ChildStage(int id) {
			vbox = new VBox();
			
		Scene scene = new Scene(vbox, 250, 100);
			
			setScene(scene);
			
			setX(100);
			setY(id * 120);
			setTitle("窗口 #" + id);
		}

		@Override
		public void onSetColorClicked(Color c) {
			vbox.setBackground(new Background(new BackgroundFill(c, null, null)));
		}

		@Override
		public void onCloseClicked() {
			this.close();
		}
	}
	
	interface ParentStageActionHandler {
		void onSetColorClicked(Color color);
		
		void onCloseClicked();
	}
}
